<template>
  <div class="page">

    <el-form ref="addForm" :model="addForm" :rules="addFormRules" label-width="140px" :disabled="status == 3">
      <div class="title">基础信息</div>
      <div class="base_info">
        <el-form-item label="医生名称：" prop="name">
          <el-input v-model="addForm.name" />
        </el-form-item>
        <el-form-item label="个人职称：">
          <el-input v-model="addForm.personalTitle" />
        </el-form-item>
        <el-form-item label="所在城市：" prop="city">
          <el-select v-model="addForm.city" filterable class="a_select" @change="getHospital">
            <el-option v-for="(item,index) in cityList" :key="index" :label="item.name" :value="item.code" />
          </el-select>
        </el-form-item>
        <el-form-item label="所在医院：" prop="hospitalId">
          <el-select v-model="addForm.hospitalId" class="a_select">
            <el-option v-for="(item,index) in hospitalList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="擅长项目：" prop="expertProject">
          <el-select v-model="addForm.expertProject" multiple class="a_select">
            <el-option v-for="(item,index) in projectList" :key="index" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="从业年限：">
          <el-input v-model="addForm.workYears" />
        </el-form-item>
        <el-form-item label="执业编号：">
          <el-input v-model="addForm.practiceLicenseNo" />
        </el-form-item>
        <!-- <el-form-item></el-form-item> -->
        <el-form-item label="职业许可证：">
          <el-upload
            :action="COMMONFILEUPLOAD"
            list-type="picture-card"
            :file-list="addForm.practiceLicense"
            :limit="1"
            :headers="uploadHeaders"
            :on-success="(response, file, fileList) =>
              onSuccess(response, file, fileList, 'practiceLicense')"
            :on-remove="(file,fileList) => onRemove(file,fileList,'practiceLicense')"
            :on-preview="previewImage"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
      </div>

      <div class="title">详细介绍</div>
      <el-form-item label="医生图片：">
        <el-upload
          :action="COMMONFILEUPLOAD"
          list-type="picture-card"
          :file-list="addForm.photo"
          :limit="1"
          :headers="uploadHeaders"
          :on-success="(response, file, fileList) =>
            onSuccess(response, file, fileList, 'photo')"
          :on-remove="(file,fileList) => onRemove(file,fileList,'photo')"
          :on-preview="previewImage"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>
      <el-form-item label="医生介绍：">
        <wang-editor :key="randomKey" :value="addForm.introduce" @change="(res) => editorChange(res, 'introduce')" />
      </el-form-item>

      <el-form-item label="医生荣誉：">
        <wang-editor :key="randomKey" :value="addForm.honor" @change="(res) => editorChange(res, 'honor')" />
      </el-form-item>

      <el-form-item label="个人海报：">
        <el-upload
          :action="COMMONFILEUPLOAD"
          list-type="picture-card"
          :file-list="addForm.poster"
          :limit="1"
          :headers="uploadHeaders"
          :on-success="(response, file, fileList) =>
            onSuccess(response, file, fileList, 'poster')"
          :on-remove="(file,fileList) => onRemove(file,fileList,'poster')"
          :on-preview="previewImage"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>

      <el-form-item label="">
        <el-button type="primary" :loading="loading" @click="saveInfo">保 存</el-button>
        <el-button type="default" @click="goBack()">取 消</el-button>
      </el-form-item>

    </el-form>

    <!-- 图片预览 开始 -->
    <el-dialog custom-class="preview_dialog" :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <!-- 图片预览 开始 -->

  </div>
</template>
<script>
import WangEditor from '@/components/wangEditor'
import {
  COMMONFILEUPLOAD,
  GETPROJECTOPTIONS,
  GETCITYOPTIONS
} from '@/http/system'
import { GETHOSPITALOPTIONS } from '@/http/hospital'
import {
  ADDDOCTORINFO,
  GETDOCTORINFO,
  EDITDOCTORINFO,
  BASEURL
} from '@/http/doctor'
import { deepClone, showToast } from '@/common/util'
export default {
  components: {
    WangEditor
  },
  data() {
    return {
      addForm: {},
      randomKey: '',
      areaRows: 5,
      areaResize: 'none',
      COMMONFILEUPLOAD: COMMONFILEUPLOAD,
      uploadHeaders: {},
      addFormRules: {
        name: [{ required: true, message: '请输入医院名称', trigger: 'blur' }],
        city: [{ required: true, message: '请选择城市', trigger: 'change' }],
        hospitalId: [
          { required: true, message: '请选择医院', trigger: 'change' }
        ]
      },
      cityList: [],
      projectList: [],
      hospitalList: [],
      loading: false,
      status: '',
      dialogImageUrl: '',
      dialogVisible: false
    }
  },
  mounted() {
    const o = this.$route.query
    /**
     * 新增：status：1
     * 编辑：status：2
     * 详情：status：3
     */
    this.status = o.status
    if (o.id) {
      // let txt = "编辑医生";
      // if (o.status == 3) {
      //   txt = "医生详情";
      // }
      // document.getElementById("lastBreadcrumb").innerText = txt;
      this.getInfo(o.id)
    }

    const token = sessionStorage.getItem('token')
    this.uploadHeaders = { Authorization: token }
    this.getCity()
    this.getProject()
  },
  methods: {
    // 监听富文本输入
    editorChange(e, id) {
      this.$set(this.addForm, id, e)
    },

    /** 监听文件上传成功 */
    onSuccess(response, file, fileList, id) {
      if (response.code == 200) {
        const obj = this.addForm[id] || []
        const n = {}
        n.name = response.data
        n.url = BASEURL + response.data
        n.path = response.data
        obj.push(n)
        // this.$set(this.addForm, id, response.data);
        this.$set(this.addForm, id, obj)
      }
    },

    // 获取所有城市
    getCity() {
      GETCITYOPTIONS().then((res) => {
        this.cityList = res.data || []
      })
    },

    // 获取所有项目
    getProject() {
      GETPROJECTOPTIONS().then((res) => {
        this.projectList = res.data || []
      })
    },

    // 获取所有医院
    getHospital(code) {
      const oParams = {}
      oParams.city = code

      if (this.addForm.hospitalId) {
        delete this.addForm.hospitalId
      }

      GETHOSPITALOPTIONS(oParams).then((res) => {
        this.hospitalList = res.data || []
      })
    },

    // 保存医生信息
    saveInfo() {
      const _this = this
      _this.$refs.addForm.validate((valid) => {
        if (!valid) {
          return false
        }
        const oParams = deepClone(_this.addForm)
        oParams.expertProject = oParams.expertProject.toString()

        if (oParams.city) {
          const o = _this.cityList.find((k) => k.code == oParams.city)
          oParams.cityName = o ? o.name : ''
        }

        // 设置职业许可证
        if (oParams.practiceLicense && oParams.practiceLicense.length > 0) {
          oParams.practiceLicense = oParams.practiceLicense[0].path
        } else {
          delete oParams.practiceLicense
        }

        // 设置医生图片
        if (oParams.poster && oParams.poster.length > 0) {
          oParams.poster = oParams.poster[0].path
        } else {
          delete oParams.poster
        }

        // 设置医生图片
        if (oParams.photo && oParams.photo.length > 0) {
          oParams.photo = oParams.photo[0].path
        } else {
          delete oParams.photo
        }

        _this.loading = true

        // 编辑医生
        if (oParams.id) {
          EDITDOCTORINFO(oParams).then((res) => {
            _this.loading = false
            if (res.code == 200) {
              showToast({
                message: '编辑成功',
                type: 'success'
              })
              _this.goBack()
            }
          })
          return false
        }

        console.log(oParams)
        ADDDOCTORINFO(oParams).then((res) => {
          _this.loading = false
          if (res.code == 200) {
            showToast({
              message: '新增成功',
              type: 'success'
            })
            _this.goBack()
          }
        })
      })
    },

    // 返回
    goBack() {
      this.$router.go(-1)
    },

    // 获取医生详情
    getInfo(id) {
      const oParams = { id: id }
      GETDOCTORINFO(oParams).then((res) => {
        const obj = res.data

        if (obj.city) {
          this.getHospital(obj.city)
        }

        // 设置擅长项目
        if (obj.expertProject) {
          const arr = []
          obj.expertProject.split(',').map((k) => {
            arr.push(Number(k))
          })

          obj.expertProject = arr
        }

        // 设置职业许可证
        if (obj.practiceLicense) {
          obj.practiceLicense = [
            {
              name: obj.practiceLicense,
              url: BASEURL + obj.practiceLicense,
              path: obj.practiceLicense
            }
          ]
        } else {
          obj.practiceLicense = []
        }

        // 设置医生图片
        if (obj.poster) {
          obj.poster = [
            { name: obj.poster, url: BASEURL + obj.poster, path: obj.poster }
          ]
        } else {
          obj.poster = []
        }

        // 设置医生图片
        if (obj.photo) {
          obj.photo = [
            { name: obj.photo, url: BASEURL + obj.photo, path: obj.photo }
          ]
        } else {
          obj.photo = []
        }

        this.addForm = { ...obj }
        this.randomKey = Math.random()
      })
    },

    /** 删除文件 */
    onRemove(file, fileList, id) {
      console.log(fileList)
      this.$set(this.addForm, id, fileList)
    },

    // 预览图片
    previewImage(e) {
      console.log(e)
      this.dialogVisible = true
      this.dialogImageUrl = e.url
    }
  }
}
</script>
<style lang="scss">
.el-dialog__wrapper{
  z-index:99999 !important
}
.v-modal{
  z-index:99998 !important;
}
</style>
<style lang="scss" scoped>
.page {
  background: #fff;
  border-radius: 6px;
  padding: 0 16px;
  overflow: hidden;
}
.title {
  font-size: 20px;
  font-family: PingFang SC-Medium, PingFang SC;
  font-weight: bold;
  color: #000000;
  margin: 24px 0;
}
.base_info {
  display: flex;
  flex-wrap: wrap;
  .el-form-item {
    flex: 0 0 50%;
  }
}
.show_tips {
  display: flex;
  line-height: 1.8;
  margin: 10px 0;
  .name {
    flex-shrink: 0;
  }
  .txt {
    flex: 1;
    .cred {
      color: #f00;
    }
  }
}
.a_select {
  width: 100%;
}
</style>
